package com.jp.knowledge.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.util.SharedUtil;
import com.jp.knowledge.webUtil.JavaScriptInterface;
import com.jp.knowledge.webUtil.X5WebView;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;

import org.xutils.view.annotation.ViewInject;

public class WebMainActivity extends SlidingActivity {

	//雷达
	public static final String follow="follow";//雷达
	public static final String headlines="headlines";//头条
	public static final String experience="experience";//体验
	public static final String discover="discover";//发现
	public static final String mine="mine";//发现我的
	@ViewInject(R.id.no_content)
	private LinearLayout noContentLayout;
	@ViewInject(R.id.web_main_layout)
	private FrameLayout mViewParent;

	@ViewInject(R.id.progressBar1)
	private ProgressBar mPageLoadingProgressBar;

	private boolean loadError=false;

	private X5WebView contView;
//	private String url = "http://192.168.32.27:3001/";// "http://192.168.32.65:8080/test/test.html";
	private String url = "http://debugm.jp580.com/";// "http://192.168.32.65:8080/test/test.html";
	// //
	private String curUrl;

	private String curlPath;
	private TextView startPage;// 启动页

	public static String[] web_module_name = new String[]{"headlines", "follow", "experience", "discover", "mine"};// 头条、关注、轻体验、发现、我的  headlines   follow  compete  discover mine  竞爆compete
	@Override
	protected int getResourceId() {
		return R.layout.activity_web_main;
	}
	private LocalBroadcastManager  localBroadcastManager;
	@Override
	protected void init() {
		initView();
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
//			String  str = msg.obj.toString();
			L.e("WebMainActivity========"+msg.obj.toString());
			//{"type":"toNative","param":"Follow"}
			JsonObject obj = JsonUtil.getInstance().strToJson(msg.obj.toString());
			if(obj==null)return ;
			String type = obj.get("type")==null?"":obj.get("type").getAsString();
			if(type.equals("toNative")) {
				startActivity(new Intent(mContext, JpMainActivity.class));
//				finish();
			}else if(type.equals("show_web")){
				L.e("切换了页面成功!");
//				contView.setVisibility(View.VISIBLE);
//				//延时500ms加载
				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						Message msg = mHandler.obtainMessage();
						msg.what=11;
						msg.obj="{'type':''}";
						mHandler.sendMessage(msg);
					}
				},500);

			}else if(msg.what==11){

				sendLoadingCompeleteBroadcast();//发现加载完成广播  跳到页面
				loading.cancel();
//				ToasUtil.toast(context,"111111");
				contView.setVisibility(View.VISIBLE);
			}else if(type.equals("postUserDataToNative")){//h5端登录成功
				try {
					JsonObject json = obj.get("param").getAsJsonObject();
					UserData userData = JsonUtil.getInstance().jsonToObject(json,UserData.class);
					if(userData!=null&&userData.getIsLogin()==1){
						application.setUserData(userData);

						//发送登录成功新广播
						Intent intent = new Intent();
						intent.setAction(LocalBroadCast.GET_LOGIN_INFO);
						localBroadcastManager.sendBroadcast(intent);
						HttpHelper.token=userData.getToken();
						HttpHelper.uuid=userData.getUuid();
						SharedUtil.getInstance(mContext).saveTokenAndUUId(HttpHelper.token,HttpHelper.uuid);
					}

					L.e("postUserDataToNative",userData.toString());
				}catch (Exception e){

				}
			}else if(type.equals("set_user_data")){//设置用户信息回调
				L.e("WebMainActivity","设置用户信息回调");
			}
		}
	};

	private void sendLoadingCompeleteBroadcast() {
		Intent intent = new Intent(LocalBroadCast.WEB_LOADING_BROAD);
		localBroadcastManager.sendBroadcast(intent);
	}

	/**
	 * 初始view
	 */
	private void initView() {
		localBroadcastManager = LocalBroadcastManager.getInstance(mContext);

//		application.setWebMainActivity(this);
//		QbSdk.allowThirdPartyAppDownload(true);
		contView = initWebView();//(X5WebView) findViewById(R.id.content);
//		contView.getSettings().setDomStorageEnabled(true);
		contView.getSettings().setUserAgentString("app_jp;jp580.com");

//		X5WebView.setSmallWebViewEnabled(true);// 开启webview窗口转移功能
		contView.addJavascriptInterface(new JavaScriptInterface(mHandler), "Android");
//		contView.setUrlHandler(new X5WebView.UrlHandler() {
//			@Override
//			public void handUrl(String ul) {
//				curUrl = ul;
//				noContentLayout.setVisibility(View.GONE);
//				L.e("WebMainActivity");
//			}
//
//			@Override
//			public void handError(WebView webView, int i, String s, String s1) {
//				contView.setVisibility(View.VISIBLE);
//				noContentLayout.setVisibility(View.VISIBLE);
//				loadError=true;
//			}
//		});
//		contView.loadUrl(url);
		contView.loadUrl("file:///android_asset/jp580/index.html");
//		contView.loadUrl("javascript:windowNativeBridge.setInWebView(2)");
		noContentLayout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				contView.loadUrl(url);
				if(curlPath!=null)
				setCurrentPath(curlPath);
			}
		});
	}

	@Override
	protected void onResume() {
//		getIntent().getExtras();
		super.onResume();
		L.e("webmainactivity=====onResume");
//		setCurrentPath("follow/themeList");
	}

	public    void setCurrentPath(String path){
		this.curlPath = path;
		contView.loadUrl("javascript:windowNativeBridge.setInWebView(2)");
		L.e("setCurrentPath",path);
		if(contView!=null) {
			loading.show();
//			contView.setVisibility(View.GONE);
			JsonObject obj = new JsonObject();
			obj.addProperty("type","show_web");

//			contView.loadUrl("javascript:windowNativeBridge.setCurrentPath('" + path + "'),Android.jsCallback('"+obj.toString()+"')");//设置当前页面路径
//           contView.setVisibility(View.GONE);
			contView.loadUrl("javascript:windowNativeBridge.setCurrentPath('" + path + "','"+obj.toString()+"')");
		}
	}


	/**
	 * 设置用户信息到h5里面
	 * @param userData
     */
	public void setUserData(UserData userData){
		String data = userData==null?"{}":JsonUtil.getInstance().objToJson(userData);
		JsonObject obj = new JsonObject();
		obj.addProperty("type","set_user_data");
		L.e("本次设置h5的用户信息为:"+data);
//		contView.loadUrl("javascript:windowNativeBridge.setUserInfoData('"+data+"',Android.jsCallback('"+obj.toString()+"'))");
		contView.loadUrl("javascript:windowNativeBridge.setUserInfoData('"+data+"','"+obj.toString()+"')");
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(loadError){
			this.finish();
		}else{
			if (keyCode == KeyEvent.KEYCODE_BACK && contView.canGoBack()) {
				contView.loadUrl("javascript:windowNativeBridge.goBack()");
				return true;
			}else{
				startActivity(new Intent(mContext,JpMainActivity.class));
//				this.finish();
				return true;
			}
		}
		return super.onKeyDown(keyCode,event);
	}





	private X5WebView initWebView(){
		Log.e("0819", " before is " + System.currentTimeMillis());
		final X5WebView mWebView = new X5WebView(this);
		Log.e("0819", " after is " + System.currentTimeMillis());


		Log.w("grass", "Current SDK_INT:" + Build.VERSION.SDK_INT);

		mViewParent.addView(mWebView, new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.FILL_PARENT,
				FrameLayout.LayoutParams.FILL_PARENT));

		initProgressBar();

		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return false;
			}

			@Override
			public WebResourceResponse shouldInterceptRequest(WebView view,
															  WebResourceRequest request) {
				// TODO Auto-generated method stub

				Log.e("should", "request.getUrl().toString() is " + request.getUrl().toString());

				return super.shouldInterceptRequest(view, request);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				if(url.equals(WebMainActivity.this.url)&&curlPath!=null){
					setCurrentPath(curlPath);
				}
//				loading.cancel();
			}

			@Override
			public void onReceivedError(WebView webView, int i, String s, String s1) {
				L.e("onReceivedError","网页加载错误......." + "i=" + i + "=====s=" + s + "===s1=" + s1);
				loading.cancel();
				webView.stopLoading();
				webView.clearView();
				noContentLayout.setVisibility(View.VISIBLE);
//				loadError=true;
//				webView.loadUrl("file:///android_asset/error.html");

			}

		});

		mWebView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onReceivedTitle(WebView view, String title) {
				L.d("title: " + title);
//				if (!mWebView.getUrl().equalsIgnoreCase(mHomeUrl)) {
//				} else {
//				}
			}

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				// TODO Auto-generated method stub
				final int progress = newProgress;
				mPageLoadingProgressBar.setProgress(newProgress);
				if (mPageLoadingProgressBar != null && newProgress != 100) {
					mPageLoadingProgressBar.setVisibility(View.VISIBLE);
				} else if (mPageLoadingProgressBar != null) {
					mPageLoadingProgressBar.setVisibility(View.GONE);
				}
//				handler.postDelayed(new Runnable() {
//					@Override
//					public void run() {
//						if(progress<100){
//							Message msg = handler.obtainMessage();
//							msg.obj=url;
//							handler.sendMessage(msg);
//						}
//					}
//				},20*1000);
			}
		});

		mWebView.setDownloadListener(new DownloadListener() {

			@Override
			public void onDownloadStart(String arg0, String arg1, String arg2,
										String arg3, long arg4) {
				L.d("url: " + arg0);
				new AlertDialog.Builder(mContext)
						.setTitle("你即将下载")
						.setPositiveButton("yes",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
														int which) {
										ToasUtil.toast(
												mContext,
												"fake message: i'll download...");
									}
								})
						.setNegativeButton("no",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
														int which) {
										// TODO Auto-generated method stub
										ToasUtil.toast(
												mContext,
												"fake message: refuse download...");
									}
								})
						.setOnCancelListener(
								new DialogInterface.OnCancelListener() {

									@Override
									public void onCancel(DialogInterface dialog) {
										// TODO Auto-generated method stub
										ToasUtil.toast(
												mContext,
												"fake message: refuse download...");
									}
								}).show();
			}
		});


		WebSettings webSetting = mWebView.getSettings();
		webSetting.setAllowFileAccess(true);
		webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		webSetting.setSupportZoom(true);
		webSetting.setBuiltInZoomControls(true);
		webSetting.setUseWideViewPort(true);
		webSetting.setSupportMultipleWindows(false);
		webSetting.setLoadWithOverviewMode(true);
		webSetting.setAppCacheEnabled(true);
		webSetting.setDatabaseEnabled(true);
		webSetting.setDomStorageEnabled(true);
		webSetting.setJavaScriptEnabled(true);
		webSetting.setGeolocationEnabled(true);
		webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
		webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
		webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
		webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
				.getPath());
		// webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
		webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
		webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
		// webSetting.setPreFectch(true);
		long time = System.currentTimeMillis();
//		if (mIntentUrl == null) {
//			mWebView.loadUrl(mHomeUrl);
//		} else {
//			mWebView.loadUrl(mIntentUrl.toString());
//		}
		TbsLog.d("time-cost", "cost time: "
				+ (System.currentTimeMillis() - time));
		CookieSyncManager.createInstance(this);
		CookieSyncManager.getInstance().sync();
		return  mWebView;
	}


	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
//            super.handleMessage(msg);
			contView.loadUrl(msg.obj.toString());
		}
	};
	private void initProgressBar() {
		// ProgressBar(getApplicationContext(),
		// null,
		// android.R.attr.progressBarStyleHorizontal);
		mPageLoadingProgressBar.setMax(100);
		mPageLoadingProgressBar.setProgressDrawable(this.getResources()
				.getDrawable(R.drawable.color_progressbar));
	}

	@Override
	protected void onPause() {
		super.onPause();
		Intent intent = new Intent(LocalBroadCast.GET_ATTION_DATA_BROAD);
		localBroadcastManager.sendBroadcast(intent);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}



}
